/*txBx9FIYfUQl2UukqRyP7yZAQjenf+1adeilhAiKzCRgS1A5Mx9hjQJlpB0IBJF8*/
/*
 * @Author: xiahui
 * @PageInfo: 卡片保存
 * @Date: 2019-01-16 15:21:19
 * @Last Modified by: zhr
 * @Last Modified time: 2021-10-22 14:04:24
 */
import { ajax } from 'nc-lightapp-front';
import {
	PAGECODE,
	AREA,
	UISTATUS,
	URL,
	FIELDS,
	CARDTABLEAREAIDS,
	CACHESTATUS,
	FSTATUSFLAG,
	DATASOURCECACHE,
	TEMPSAVECONFIG
} from '../../constance';
import { showSuccessInfo, showWarningInfo, showErrorInfo } from '../../../../../scmpub/scmpub/pub/tool/messageUtil';
import { setCardPage, setCardCacheData } from '../../utils/cardPageUtil';
import { setDefData, rewriteTransferSrcBids, getDefData } from '../../../../../scmpub/scmpub/pub/cache';
import { getLangByResId } from '../../../../../scmpub/scmpub/pub/tool/multiLangUtil';
import ScriptActionDlg from '../../../pub/components/ScriptActionDlg';
import { showResumeModal } from 'scmpub/scmpub/components/ResumeModal';

export default function saveBtnClick(props, skipCodes, callBack) {
	//过滤表中空行
	filterEmptyRows(props);
	//暂存保存
	let tempsave = getDefData(DATASOURCECACHE.tempCardCacheKey, TEMPSAVECONFIG.tempsave);
	let flag = props.validatePageToToast([
		{
			// creteForm 使用的areaCode
			name: [ AREA.cardFormId ],
			type: 'form'
		},
		{
			// createCardTable的areaCode，多页签区域填主表就行
			name: CARDTABLEAREAIDS,
			type: 'cardTable'
		}
	]);
	if (!flag.allPassed) {
		return;
	}
	let data = props.createExtCardData(PAGECODE.cardPagecode, AREA.cardFormId, CARDTABLEAREAIDS);
	let status = props.getUrlParam('status');
	let source = props.getUrlParam('source');

	if (source && !data.head.head.rows[0].values[FIELDS.pk_ct_pu].value) {
		// 复制时，设置表头为新增状态
		data.head.head.rows[0].status = '2';
	}

	//暂存保存，将表头设置为新增
	if (tempsave) {
		data.head.head.rows[0].status = '2';
	}

	// 新增保存，需要把删除的行剔除掉
	if (data.head.head.rows[0].status == '2') {
		CARDTABLEAREAIDS.forEach((areaId) => {
			if (data.bodys[areaId]) {
				let newRows = [];
				data.bodys[areaId].rows.forEach((row) => {
					if (row.status != '3') {
						newRows.push(row);
					}
				});
				data.bodys[areaId].rows = newRows;
			}
		});
	}

	// 重置伪列
	data.bodys[AREA.cardTableId].rows.map((row, index) => {
		if (row.status != 3) {
			// 设置pseudocolumn字段值，用于前后台合并
			row.values.pseudocolumn.value = index + '';
		}
	});

	//付款协议设置伪列
	data.bodys[AREA.cardPayId].rows.map((row, index) => {
		if (row.status != 3) {
			// 设置pseudocolumn字段值，用于前后台合并
			row.values.pseudocolumn = { value: index + '' };
		}
	});

	skipCodes = skipCodes ? skipCodes : new Array();
	data['skipCodes'] = skipCodes;

	if (status == UISTATUS.modify) {
		let fstatusflag = data.head.head.rows[0].values[FIELDS.fstatusflag].value;
		if (fstatusflag != FSTATUSFLAG.validate && fstatusflag != FSTATUSFLAG.free) {
			showErrorInfo(getLangByResId(this, '4004PURDAILY-000065')); /* 国际化处理： 单据状态不正确, 不能进行变更！*/
			return;
		}
		let allRows = props.cardTable.getAllRows(AREA.cardChangeId);
		let maxIndex = 0; //最大版本号的 index
		let maxVersion = 0; //最大版本号
		allRows.forEach((item, index) => {
			let version = 0;
			if (item.values[FIELDS.vchangecode]) {
				version = parseInt(item.values[FIELDS.vchangecode].value);
			}
			if (version > maxVersion) {
				maxVersion = version;
				maxIndex = index;
			}
		});
		let vchgreason = data.bodys[AREA.cardChangeId].rows[maxIndex].values[FIELDS.vchgreason].value;
		if (!vchgreason) {
			// 无变更原因，弹出提示框
			this.reason = null;
			props.modal.show('ScriptActionDlg', {
				title: getLangByResId(this, '4004PURDAILY-000024') /* 国际化处理： 原因*/,
				hasCloseBtn: true,
				userControl: true,
				content: (
					<ScriptActionDlg
						changeData={this.changeReason.bind(this)}
						title={getLangByResId(this, '4004PURDAILY-000025')}
					/>
				) /* 国际化处理： 请输入变更原因*/,
				beSureBtnClick: () => {
					if (this.reason) {
						data.bodys[AREA.cardChangeId].rows[maxIndex].values[FIELDS.vchgreason].value = this.reason;
						props.cardTable.setValByKeyAndIndex(AREA.cardChangeId, maxIndex, FIELDS.vchgreason, {
							value: this.reason
						});
						doModify.call(this, props, data, skipCodes, callBack);
						props.modal.close('ScriptActionDlg');
					} else {
						showWarningInfo(null, getLangByResId(this, '4004PURDAILY-000026')); /* 国际化处理： 请输入变更原因！*/
					}
				},
				cancelBtnClick: () => {
					props.modal.close('ScriptActionDlg');
				}
			});
			return;
		} else {
			doModify.call(this, props, data, skipCodes, callBack);
		}
	} else {
		props.validateToSave(data, () => {
			ajax({
				url: URL.save,
				data: data,
				success: (res) => {
					if (res.formulamsg && res.formulamsg instanceof Array && res.formulamsg.length > 0) {
						props.dealFormulamsg(res.formulamsg);
					}
					if (res.success && res.data) {
						// 交互式异常处理
						if (res.data.isResume && res.data.isResume == true) {
							if (res.data.url) {
								res.data.url = '../../../../' + res.data.url;
							}
							showResumeModal.bind(this)(
								props,
								'ResumeMessageDlg',
								skipCodes,
								res.data,
								saveBtnClick.bind(this, props, skipCodes, callBack)
							);
							return;
						}
						if (source) {
							// 转单情况
							// 更新页面数据
							setCardPage.call(this, props, res.data, true, UISTATUS.browse);
							if (callBack) {
								// 保存提交
								callBack.call(this, props, skipCodes, () => {
									props.transferTable.setTransformFormStatus(AREA.cardLeftId, {
										status: true,
										onChange: (current, next, currentIndex) => {}
									});
								});
							} else {
								props.setUrlParam({ status: UISTATUS.browse });
								props.transferTable.setTransformFormStatus(AREA.cardLeftId, {
									status: true,
									onChange: (current, next, currentIndex) => {}
								});
							}
							// 回写上游来源单据bid
							rewriteTransferSrcBids(props, 'csrcbid', res.data.bodys[AREA.cardTableId].rows);
						} else {
							// 非转单情况
							let pk = props.form.getFormItemsValue(AREA.cardFormId, FIELDS.pk_ct_pu).value;
							props.setUrlParam({ status: UISTATUS.browse, id: pk });
							// 更新页面数据
							setCardPage.call(this, props, res.data, true, UISTATUS.browse);
							//处理保存及提交场景
							if (callBack) {
								callBack.call(this, props, skipCodes);
							}
						}
						if (
							status == UISTATUS.add ||
							status == UISTATUS.copy ||
							status == UISTATUS.ref20 ||
							status == UISTATUS.ref28
						) {
							// 缓存处理
							setCardCacheData.call(this, props, res.data, CACHESTATUS.add);
						}

						// 提示
						showSuccessInfo(getLangByResId(this, '4004PURDAILY-000027')); /* 国际化处理： 保存成功*/
					}
				}
			});
		});
	}
	setDefData(DATASOURCECACHE.tempCardCacheKey, 'tempsave', false);
}

function filterEmptyRows(props) {
	props.cardTable.filterEmptyRows(
		AREA.cardTableId,
		[
			FIELDS.pk_material,
			FIELDS.pk_marbasclass,
			FIELDS.cunitid,
			FIELDS.nnum,
			FIELDS.nqtorigprice,
			FIELDS.nqtorigtaxprice,
			FIELDS.norigtaxmny
		],
		'include'
	);
	props.cardTable.filterEmptyRows(
		AREA.cardTermId,
		[ FIELDS.vtermcode, FIELDS.vtermcontent, FIELDS.votherinfo, FIELDS.vmemo ],
		'include'
	);
	props.cardTable.filterEmptyRows(AREA.cardFeeId, [ FIELDS.vexpcode, FIELDS.vexpsum, FIELDS.vmemo ], 'include');
	props.cardTable.filterEmptyRows(AREA.cardMemoraId, [ FIELDS.vmemoracode, FIELDS.vmemo ], 'include');
	props.cardTable.filterEmptyRows(AREA.cardChangeId, [ FIELDS.vchangecode ], 'include');
	props.cardTable.filterEmptyRows(
		AREA.cardPayId,
		[ FIELDS.accrate, FIELDS.pk_payperiod, FIELDS.pk_balatype ],
		'include'
	);
}

/**
 * 变更请求
 * @param {*} props
 * @param {*} data
 * @param {*} callBack
 */
function doModify(props, data, skipCodes, callBack) {
	ajax({
		url: URL.modify,
		data: data,
		success: (res) => {
			if (res.formulamsg && res.formulamsg instanceof Array && res.formulamsg.length > 0) {
				props.dealFormulamsg(
					res.formulamsg //参数一：返回的公式对象
				);
			}
			if (res.success && res.data) {
				// 交互式异常处理
				if (res.data.isResume && res.data.isResume == true) {
					if (res.data.url) {
						res.data.url = '../../../../' + res.data.url;
					}
					showResumeModal.bind(this)(
						props,
						'ResumeMessageDlg',
						skipCodes,
						res.data,
						saveBtnClick.bind(this, props, skipCodes, callBack)
					);
					return;
				}
				let pk = props.form.getFormItemsValue(AREA.cardFormId, FIELDS.pk_ct_pu).value;
				props.setUrlParam({ status: UISTATUS.browse });
				setCardPage.call(this, props, res.data);
				setCardCacheData.call(this, props, res.data, CACHESTATUS.modify, pk);
				showSuccessInfo(getLangByResId(this, '4004PURDAILY-000028')); /* 国际化处理： 变更成功*/
				//处理保存及提交场景
				if (callBack) {
					callBack.call(this, props, skipCodes);
				}
			}
		}
	});
}

/*txBx9FIYfUQl2UukqRyP7yZAQjenf+1adeilhAiKzCRgS1A5Mx9hjQJlpB0IBJF8*/